package services

import (
	"errors"
	"go-mvc-ecommerce/models"

	"gorm.io/gorm"
)

type OrderService struct {
	db *gorm.DB
}

func NewOrderService(db *gorm.DB) *OrderService {
	return &OrderService{db: db}
}

// 购买商品
func (s *OrderService) PurchaseProduct(userID, productID uint, quantity int) (*models.Order, error) {
	var order *models.Order

	// 开启手动事务
	tx := s.db.Begin()
	if tx.Error != nil {
		return nil, tx.Error
	}

	// 使用defer确保事务被正确处理
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// 1. 获取用户信息
	var user models.User
	if err := tx.First(&user, userID).Error; err != nil {
		tx.Rollback()
		return nil, errors.New("没有找到用户")
	}

	// 2. 获取商品信息
	var product models.Product
	if err := tx.First(&product, productID).Error; err != nil {
		tx.Rollback()
		return nil, errors.New("没有找到商品")
	}

	// 3. 检查库存
	if product.Stock < quantity {
		tx.Rollback()
		return nil, errors.New("库存不足")
	}

	// 4. 计算总金额并检查用户余额
	totalAmount := product.Price * float64(quantity)
	if user.Balance < totalAmount {
		tx.Rollback()
		return nil, errors.New("金额不足")
	}

	// 5. 更新用户余额
	newBalance := user.Balance - totalAmount
	if err := tx.Model(&user).Update("balance", newBalance).Error; err != nil {
		tx.Rollback()
		return nil, err
	}

	// 6. 更新商品库存
	newStock := product.Stock - quantity
	if err := tx.Model(&product).Update("stock", newStock).Error; err != nil {
		tx.Rollback()
		return nil, err
	}

	// 7. 创建订单
	order = &models.Order{
		UserID:      userID,
		ProductID:   productID,
		Quantity:    quantity,
		TotalAmount: totalAmount,
		Status:      "completed",
	}

	if err := tx.Create(order).Error; err != nil {
		tx.Rollback()
		return nil, err
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		return nil, err
	}

	return order, nil
}

// 获取用户订单
func (s *OrderService) GetUserOrders(userID uint) ([]models.Order, error) {
	var orders []models.Order
	result := s.db.Where("user_id = ?", userID).Find(&orders)
	if result.Error != nil {
		return nil, result.Error
	}
	return orders, nil
}
